const nodeResolve = require("@rollup/plugin-node-resolve");
const commonjs = require("@rollup/plugin-commonjs");
const typescript = require("@rollup/plugin-typescript");
const { packagesDir, resolve, getPackageJson } = require("./scripts/paths");
const fs = require("fs");
const scss = require("rollup-plugin-scss");
const postcss = require("rollup-plugin-postcss");

let config = [];
// 配置打包信息
const getOutputConfigs = (name) => {
  return {
    esm: {
      file: resolve(`packages/${name}/dist/${name}.esm.js`),
      format: "es",
    },
    cjs: {
      file: resolve(`packages/${name}/dist/${name}.cjs.js`),
      format: "cjs",
    },
    global: {
      file: resolve(`packages/${name}/dist/${name}.js`),
      format: "iife",
    },
  };
};

const env = process.env.NODE_ENV; //环境变量
const comName = process.env.COMNAME; //组件包名

//获取公共包名
const commonPackageName = fs
  .readdirSync(packagesDir)
  .filter((item) => !/react|vue|taro/.test(item));
/**
 * 公共包配置生成器
 * @param {*} formatList
 * @param {*} packageName
 * @param {*} plugins
 * @param {*} external
 * @returns
 */
const markeRollupConfing = (
  formatList,
  packageName,
  plugins = [],
  external = []
) => {
  return formatList.map((type) => {
    let outputConfigs = getOutputConfigs(packageName);
    let output = outputConfigs[type];
    let pageageJson = getPackageJson(packageName);
    let tsFilePath = resolve(`packages/${packageName}/tsconfig.json`);
    let tsConfig = {
      sourceMap: false,
    };
    // 加载 tsconfig 配置文件
    if (fs.existsSync(tsFilePath)) {
      tsConfig.tsconfig = tsFilePath;
    }

    if (type === "global") {
      const name = packageName.replace("-", "");
      output.name = name;
      output.exports = "named";
    } else {
      external = external.concat([
        ...Object.keys(pageageJson.dependencies || {}),
      ]);
    }
    return {
      input: resolve(`packages/${packageName}/src/index.ts`),
      plugins: [nodeResolve(), commonjs(), typescript(tsConfig), scss()],
      external,
      output,
    };
  });
};

/**
 * 获取公共包配置
 * @param {*} commonPackageName
 * @param {*} formatList
 * @returns
 */
const getCommonRollupConfig = (commonPackageName, formatList) => {
  let list = [];
  commonPackageName.map((pageageName) => {
    let rollupConfiglist = markeRollupConfing(formatList, pageageName, []);
    list = list.concat(rollupConfiglist);
  });
  return list;
};

let formatList = [];
if (env === "prod") {
  formatList = ["esm", "cjs", "global"];
} else {
  // 开发只打包 esm 包
  formatList = ["esm"];
}
//TODO 带添加
config = getCommonRollupConfig(commonPackageName, formatList);
comName === "react-coms" &&
  config.push(
    markeRollupConfing(formatList, comName, [], ["react", "react-dom"])[0]
  );

module.exports = config;
